package com.yfbao.horizon.docker.controller;

import com.alibaba.druid.util.StringUtils;
import com.yfbao.horizon.docker.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.Base64;

@RestController
@RequestMapping("/uk")
@Slf4j
public class UkTestController {

    private static String  sidd="asdfghjk12312";

    @PostMapping(value ="/auth",consumes = "text/plain",produces = "text/xml")
    public String example5(@RequestBody String xmlPayload) {
        String service = getService(xmlPayload);
        if(service.equalsIgnoreCase("OriginalService")){
            String token = getToken(xmlPayload);
            return factoryTokenRes(token);
        }else if(service.equalsIgnoreCase("AuthenService")){
            String s = checkAuthCredential(xmlPayload);
            return factoryAuthRes(s);
        }
        return "error";
    }

    private String checkAuthCredential(String xmlPayload){
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlPayload)));
            NodeList nodeList = document.getElementsByTagName("message");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                NodeList head = element.getElementsByTagName("body");
                for(int j=0;j<head.getLength();j++){
                    Element item = (Element) head.item(i);
                    String appId = item.getElementsByTagName("appId").item(0).getTextContent();
                    if(!appId.equalsIgnoreCase("gxzjtxxxt")){
                        log.warn("unknow appid");
                        return "unknow appid";
                    }


                    NodeList authen = item.getElementsByTagName("authen");
                    Node itemAuthen = authen.item(0);
                    if(itemAuthen ==null){
                        log.warn("unknow itemAuthen");
                        return "unknow authen";
                    }
                    NodeList authCredential = ((Element) itemAuthen).getElementsByTagName("authCredential");
                    for(int ii=0;ii<authCredential.getLength();ii++){
                        Element itemCredential = (Element) authCredential.item(i);
                        String original = itemCredential.getElementsByTagName("original").item(0).getTextContent();
                        // 解码Base64编码的字符串
                        byte[] decodedBytes = Base64.getDecoder().decode(original);
                        // 将字节转换成字符串
                        String decodedString = new String(decodedBytes);
                        if(original.equals(sidd) || decodedString.equals(sidd)){
                            return "";
                        }
                    }
                    return "unknow error";
                }
            }
        }catch (Exception e){
            log.error("解析xml异常",e);
        }
        return "解析xml异常";
    }

    private String getService(String xmlPayload){
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlPayload)));
            NodeList nodeList = document.getElementsByTagName("message");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                NodeList head = element.getElementsByTagName("head");
                for(int j=0;j<head.getLength();j++){
                    Element item = (Element) head.item(i);
                    String version = item.getElementsByTagName("version").item(0).getTextContent();
                    Node servicetype = item.getElementsByTagName("servicetype").item(0);
                    if(servicetype !=null){
                        return servicetype.getTextContent();
                    }
                    Node serviceType = item.getElementsByTagName("serviceType").item(0);
                    if(serviceType !=null){
                        return serviceType.getTextContent();
                    }
                }
            }
        }catch (Exception e){
            log.error("解析xml异常",e);
        }
        return null;
    }


    private String getToken(String xmlPayload){
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlPayload)));
            NodeList nodeList = document.getElementsByTagName("message");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                NodeList body = element.getElementsByTagName("body");
                for(int j=0;j<body.getLength();j++){
                    Element item = (Element) body.item(i);
                    String appid = item.getElementsByTagName("appid").item(0).getTextContent();
                    if(appid.equalsIgnoreCase("gxzjtxxxt")){
                        return sidd;
                    }
                }
            }
        }catch (Exception e){
           log.error("解析xml异常",e);
        }
        return null;
    }

    private String factoryTokenRes(String sid){
        StringBuilder xml = new  StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.append("<message>\n");
        xml.append("\t<head>\n");
        xml.append("\t\t<version>1.0</version>\n");
        xml.append("\t\t<servicetype>OriginalService</servicetype>\n");
        if(StringUtils.isEmpty(sid)){
            xml.append("\t\t<messagestate>true</messagestate>\n");
        }else{
            xml.append("\t\t<messagestate>false</messagestate>\n");
        }
        xml.append("\t</head>\n");
        xml.append("\t<body>\n");
        xml.append("\t\t<original>asdfghjk12312</original>\n");
        xml.append("\t</body>\n");
        xml.append("</message>");

        return xml.toString();
    }


    private String factoryAuthRes(String res){
        StringBuilder xml = new  StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.append("<message>\n");
        xml.append("\t<head>\n");
        xml.append("\t\t<version>1.0</version>\n");
        xml.append("\t\t<serviceType>AuthenService</serviceType>\n");
        if(StringUtils.isEmpty(res)){
            xml.append("\t\t<messageState>false</messageState>\n");
        }else{
            xml.append("\t\t<messageState>true</messageState>\n");
            xml.append("\t\t<messageCode>00000001</messageCode>\n");
            xml.append("\t<messageDesc>"+res+"</messageDesc>\n");
        }
        xml.append("\t</head>\n");
        xml.append("\t<body>\n");
        xml.append("\t\t<authResultSet allfailed=\"false\">\n");
        if(StringUtils.isEmpty(res)){
            xml.append("\t\t\t<authResult authMode=\"cert\" success=\"true\"></authResult>\n");
        }else {
            xml.append("\t\t\t<authResult authMode=\"cert\" success=\"false\"></authResult>\n");
        }
        xml.append("\t\t</authResultSet>\n");
        xml.append("\t\t<accessControlResult>Permit/Deny</accessControlResult>\n");
        xml.append("\t\t<attributes>\n");
        xml.append("\t\t\t<attr name=\"X509Certificate.SubjectDN\" namespace=\"”http://www.jit.com.cn/cinas/ias/ns/saml/saml11/X.509“\">cn=test,o=jit,c=cn</attr>\n");
        xml.append("\t\t\t<attr name=\"机构字典\" namespace=\"”http://www.jit.com.cn/cinas/ias/ns/saml/saml11/X.509“\">北京吉大正元</attr>\n");
        xml.append("\t\t\t<attr name=\"部门\" parentname=\"北京吉大正元\" namespace=\"”http://www.jit.com.cn/cinas/ias/ns/saml/saml11/X.509“\">产品部</attr>\n");
        xml.append("\t\t</attributes>\n");
        xml.append("\t</body>\n");
        xml.append("</message>");
        return xml.toString();
    }
    private User getUser(){
        User user = new User();
        user.setName("John Doe");
        user.setAge(30);
        return user;
    }


    public static boolean parseXml(){
        String xml= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<message>" +
                "<head>" +
                "<version>1.0</version>" +
                "<servicetype>OriginalService</servicetype>" +
                "</head>" +
                "<body>" +
                "<appid>testApp</appid>" +
                "</body>" +
                "</message>";
        try{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xml)));
            NodeList nodeList = document.getElementsByTagName("message");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element element = (Element) nodeList.item(i);
                NodeList head = element.getElementsByTagName("head");
                for(int j=0;j<head.getLength();j++){
                    Element item = (Element) head.item(i);
                    String version = item.getElementsByTagName("version").item(0).getTextContent();
                    String servicetype = item.getElementsByTagName("servicetype").item(0).getTextContent();
                    System.out.println("version: " + version+", servcie:"+servicetype);
                }
                NodeList body = element.getElementsByTagName("body");
                for(int j=0;j<body.getLength();j++){
                    Element item = (Element) body.item(i);
                    String appid = item.getElementsByTagName("appid").item(0).getTextContent();
                    System.out.println("appid: " + appid);
                }
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }

    public static void main(String[] args) {
        parseXml();
    }
}
